'use client';

import React, { useState } from 'react';
import { createPromiseClient } from '@connectrpc/connect';
import { createConnectTransport } from '@connectrpc/connect-web';
import { CalculatorService } from '@/gen/calculator_connect';
import { CalculateRequest } from '@/gen/calculator_pb';

export default function Calculator() {
  const [num1, setNum1] = useState('');
  const [num2, setNum2] = useState('');
  const [operation, setOperation] = useState('+');
  const [result, setResult] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);

  const transport = createConnectTransport({
    baseUrl: 'http://localhost:8080',
  });

  const client = createPromiseClient(CalculatorService, transport);

  const handleCalculate = async () => {
    try {
      setError(null);
      const request = new CalculateRequest({
        a: parseFloat(num1),
        b: parseFloat(num2),
        operation,
      });

      const response = await client.calculate(request);
      setResult(response.result);
    } catch (err) {
      setError('计算错误: ' + (err as Error).message);
      console.error('计算错误:', err);
    }
  };

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-lg">
      <h1 className="text-2xl font-bold mb-6 text-center">计算器</h1>
      <div className="space-y-4">
        <div>
          <input
            type="number"
            value={num1}
            onChange={(e) => setNum1(e.target.value)}
            className="w-full p-2 border rounded"
            placeholder="第一个数字"
          />
        </div>
        <div>
          <select
            value={operation}
            onChange={(e) => setOperation(e.target.value)}
            className="w-full p-2 border rounded"
          >
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">×</option>
            <option value="/">÷</option>
          </select>
        </div>
        <div>
          <input
            type="number"
            value={num2}
            onChange={(e) => setNum2(e.target.value)}
            className="w-full p-2 border rounded"
            placeholder="第二个数字"
          />
        </div>
        <button
          onClick={handleCalculate}
          className="w-full bg-blue-500 text-white p-2 rounded hover:bg-blue-600"
        >
          计算
        </button>
        {error && (
          <div className="text-red-500 text-center">
            {error}
          </div>
        )}
        {result !== null && !error && (
          <div className="text-center text-xl font-bold">
            结果: {result}
          </div>
        )}
      </div>
    </div>
  );
} 